const { getList, getDetail, newBlog, updateBlog, delBlog } = require("../controller/blog");
const { SuccessModel, ErrorModel } = require("../model/resModel");

const handleBlogRouter = (req, res) => {
  const {method,path} = req;
  const { id } = req.query;

  // 获取博客列表
  if (method == 'GET' && path == '/api/blog/list') {
    const {author = '', keyword = ''} = req.query;
    //const listData = getList(author, keyword);
    return getList(author, keyword).then((listData) => {
      return new SuccessModel(listData, '数据博客列表成功');
    })
  }

  // 获取博客详情
  if (method == 'GET' && path == '/api/blog/detail') {
    const resultDetail = getDetail(id);
    return resultDetail.then((data) => {
      return new SuccessModel(data, '获取博客详情成功');
    })
  }

  //新建一篇博客
  if (method == 'POST' && path == '/api/blog/new') {
    req.body.author = "xw"; // 先默认为xw用户
    const resultNew = newBlog(req.body);
    return resultNew.then((e) => {
      console.log("新建博客结果:",e);
      if (e.affectedRows > 0) {
        return new SuccessModel({id:e.insertId}, '新建博客成功');
      } else {
        return new ErrorModel('新建博客成功');
      }
      
    })

  }

  // 更新一篇博客
  if (method == 'POST' && path == '/api/blog/update') {
    const resultUpdate = updateBlog(id, req.body);
    return resultUpdate.then((e) => {
      console.log("更新博客结果:",e);
      if (e.affectedRows > 0) {
        return new SuccessModel('更新博客成功');
      } else {
        return new ErrorModel('更新博客失败');
      }
    })
    
  }

  // 删除一篇博客
  if (method == 'POST' && path == '/api/blog/del') {
    const author = "zhangsan";
    const resultDel = delBlog(id, author);
    return resultDel.then((e) => {
      console.log("删除博客结果:",e);
      if (e.affectedRows > 0) {
        return new SuccessModel('删除博客成功');
      } else {
        return new ErrorModel('删除博客失败');
      }
    });
  }

}

module.exports = handleBlogRouter;